import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/view/component/cell/GroupView.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/LoadingView.dart';
import 'package:im_app/im/util/ImConstant.dart';

import '../bloc/GroupSelectCubit.dart';

/// 选择一个聊天群，进行聊天
/// 进入方法： 发起群聊->选择一个群
class GroupSelectPage extends StatelessWidget {
  const GroupSelectPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<GroupSelectCubit, GroupSelectState>(
      listener: (BuildContext context, GroupSelectState groupSelectState) {
        var router = groupSelectState.forwardRouter;
        if (router == '/MessageSendPage') {
          Navigator.of(context).pushNamedAndRemoveUntil("/MessageSendPage", ModalRoute.withName('/MainPage'),
              arguments: {"id": groupSelectState.imSession?.id!, "name": groupSelectState.imSession?.name});
        }
      },
      builder: (BuildContext context, GroupSelectState state) {
        return Scaffold(
          appBar: _buildAppBar(context),
          backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
          body: SafeArea(
            left: false,
            right: false,
            child: LoadingView(
              state: state.state,
              child: Container(
                  color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
                  child: ListView.separated(
                    itemBuilder: (BuildContext context, int index) {
                      return Material(
                        color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
                        child: InkWell(
                          child: Padding(
                            padding: const EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3),
                            child: GroupView(state.allGroups.elementAt(index)),
                          ),
                          onTap: () {
                            var groupAddCubit = BlocProvider.of<GroupSelectCubit>(context);
                            groupAddCubit.add(new GroupSelectShowEvent(state.allGroups.elementAt(index)));
                          },
                        ),
                      );
                    },
                    itemCount: state.allGroups.length,
                    separatorBuilder: (BuildContext context, int index) {
                      return ListSeparator();
                    },
                  )),
            ),
          ),
        );
      },
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      leading: GestureDetector(
        child: const Icon(Icons.arrow_back),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      title: const Text('选择群聊'),
    );
  }
}
